package com.xsmart.oa.services;

import com.baomidou.mybatisplus.plugins.Page;
import com.xsmart.common.constant.ResultConstant;
import com.xsmart.common.entity.RequestBean;
import com.xsmart.common.entity.ResponseBean;
import com.xsmart.oa.dao.ShippingDAO;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.awt.image.IntegerInterleavedRaster;

import java.util.*;

/**
 * @author 周志成
 */
@Service
public class ShippingService {
    @Autowired
    ShippingDAO shippingDAO;

    /**
     * 查询配送方式
     * @param requestBean
     * @return
     */
    public ResponseBean queryShipping(RequestBean requestBean){
        int currentPage = requestBean.getRequestParamInteger("currentPage",1);
        int pageSize = requestBean.getRequestParamInteger("pageSize",10);
        String shippingCode = requestBean.getRequestParamString("shipping_code");
        String shippingName = requestBean.getRequestParamString("shipping_name");
        Map<String,Object> shippingMap = new HashMap<>();
        shippingMap.put("shipping_code",shippingCode);
        shippingMap.put("shipping_name",shippingName);
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String,Object>> page = new Page<>(currentPage,pageSize);
        try{
            page.setRecords(shippingDAO.queryShipping(page,shippingMap));
            responseBean.addResultPageItem("shippingList",page);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }

        return  responseBean;
    }

    /**
     * 新增配送方式
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addShipping(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String shippingCode = requestBean.getRequestParamString("shipping_code");
        String shippingName = requestBean.getRequestParamString("shipping_name");
        String shippingDesc = requestBean.getRequestParamString("shipping_desc");
        String insure = requestBean.getRequestParamString("insure");
        Integer supportCod = requestBean.getRequestParamInteger("support_cod");
        Integer enabled = requestBean.getRequestParamInteger("enabled");
        Map<String, Object> shippingMap = new HashMap<>(6);
        shippingMap.put("shipping_code",shippingCode);
        shippingMap.put("shipping_name",shippingName);
        shippingMap.put("shipping_desc",shippingDesc);
        shippingMap.put("insure",insure);
        shippingMap.put("support_cod",supportCod);
        shippingMap.put("enabled",enabled);
        try{
            int num = shippingDAO.addShipping(shippingMap);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    /**
     * 修改配送方式
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modShipping(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String shippingCode = requestBean.getRequestParamString("shipping_code");
        String shippingName = requestBean.getRequestParamString("shipping_name");
        String shippingDesc = requestBean.getRequestParamString("shipping_desc");
        String insure = requestBean.getRequestParamString("insure");
        Integer supportCod = requestBean.getRequestParamInteger("support_cod");
        Integer enabled = requestBean.getRequestParamInteger("enabled");
        Integer shippingId = requestBean.getRequestParamInteger("shipping_id");
        Map<String, Object> shippingMap = new HashMap<>(7);
        shippingMap.put("shipping_id",shippingId);
        shippingMap.put("shipping_code",shippingCode);
        shippingMap.put("shipping_name",shippingName);
        shippingMap.put("shipping_desc",shippingDesc);
        shippingMap.put("insure",insure);
        shippingMap.put("support_cod",supportCod);
        shippingMap.put("enabled",enabled);
        try{
            int num = shippingDAO.modShipping(shippingMap);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    /**修改模板状态
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modSellerShippingStatus(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
         Integer shippingTempletId = requestBean.getRequestParamInteger("shipping_templet_id");
        Integer shippingTempletStatus = requestBean.getRequestParamInteger("shipping_templet_status");
        if(shippingTempletStatus==1){
            shippingTempletStatus=0;
        }else{
            shippingTempletStatus=1;

        }
        try{
            int num = shippingDAO.modSellerShippingStatus(shippingTempletId,shippingTempletStatus);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }


    /**
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean modFreightTemplet(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer shippingTempletAttrId = requestBean.getRequestParamInteger("shipping_templet_attr_id");
        String shippingAreaName = requestBean.getRequestParamString("shipping_area_name");
        Integer shippingFeeType = requestBean.getRequestParamInteger("shipping_fee_type");
        Integer shippingFirstFee = requestBean.getRequestParamInteger("shipping_first_fee");
        Integer shippingSecFee = requestBean.getRequestParamInteger("shipping_sec_fee");
        Integer shippingFreeFee = requestBean.getRequestParamInteger("shipping_free_fee");
        Integer shippingGoodsFee = requestBean.getRequestParamInteger("shipping_goods_fee");
        List<String> shippingAreaId=null;
        shippingAreaId= (List<String>) requestBean.getRequestParam("shipping_area_id");
        List<String> AreaIds=shippingDAO.queryRegionId(shippingAreaId);
        String shippingAreaIds = null;
        shippingAreaIds = AreaIds.get(0);
       for(int i =1;i<AreaIds.size();i++){
           shippingAreaIds =shippingAreaIds+","+ AreaIds.get(i);
       }
        Map<String,Object> FreightTempletMap = new HashMap<>();
        FreightTempletMap.put("shippingTempletAttrId",shippingTempletAttrId);
        FreightTempletMap.put("shippingAreaName",shippingAreaName);
        FreightTempletMap.put("shippingFeeType",shippingFeeType);
        FreightTempletMap.put("shippingFirstFee",shippingFirstFee);
        FreightTempletMap.put("shippingSecFee",shippingSecFee);
        FreightTempletMap.put("shippingFreeFee",shippingFreeFee);
        FreightTempletMap.put("shippingGoodsFee",shippingGoodsFee);
        FreightTempletMap.put("shippingAreaIds",shippingAreaIds);
       try {
           int n = shippingDAO.modFreightTemplet(FreightTempletMap);
           responseBean.setResult(ResultConstant.SUCCESS);
       }catch (Exception e){
           e.printStackTrace();
           responseBean.setResult(ResultConstant.ERROR);
           throw new RuntimeException();
       }
        return responseBean;
    }

    /**
     * 删除配送方式
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean delShipping(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer shippingId = requestBean.getRequestParamInteger("shipping_id");
        try{
            int num = shippingDAO.delShipping(shippingId);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    /**删除运费模板
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean delShippingTempletAttr(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer shippingTempletAttrId = requestBean.getRequestParamInteger("shipping_templet_attr_id");
        try{
            int num = shippingDAO.delShippingTempletAttr(shippingTempletAttrId);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }



    /**查询商家与模板配送
     * @param requestBean
     * @return
     */
    public ResponseBean querySeller(RequestBean requestBean){
        int currentPage = requestBean.getRequestParamInteger("currentPage",1);
        int pageSize = requestBean.getRequestParamInteger("pageSize",10);
        String shopName = requestBean.getRequestParamString("shop_name");
        String shippingTempletName = requestBean.getRequestParamString("shipping_templet_name");
        Map<String,Object> shippingMap = new HashMap<>();
        shippingMap.put("shopName",shopName);
        shippingMap.put("shippingTempletName",shippingTempletName);
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String,Object>> page = new Page<>(currentPage,pageSize);
        try{
            page.setRecords(shippingDAO.querySeller(page,shippingMap));
            responseBean.addResultPageItem("sellerList",page);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }

        return  responseBean;
    }


    /**递归查询该城市是否存在
     * @param regionId
     * @param AreaId
     * @return
     */
    private boolean queryIsExist(Integer regionId,String[] AreaId){
        if(regionId==1){
            return false;
        }
        List<Map<String,Object>> parentIdList = shippingDAO.queryRegionParentId(regionId);
        Map<String,Object> regionMap = null;
        Iterator<Map<String, Object>> itList = parentIdList.listIterator();
        boolean b= false;
        while (itList.hasNext()) {

            Map<String, Object> region = itList.next();
            Integer rregionId = MapUtils.getInteger(region, "parent_id");
            List<Map<String,Object>> regionList = new ArrayList<>();
            String regionName = "";
            if(parentIdList.size()>0) {
                regionList = shippingDAO.queryRegionList(rregionId);
                Iterator<Map<String, Object>> itRegion = regionList.listIterator();
                while (itRegion.hasNext()) {
                    regionMap = itRegion.next();
                    regionId = MapUtils.getInteger(regionMap, "region_id");
                }

                for (int i = 0; i < AreaId.length; i++) {
                    if ((AreaId[i].trim()).equals(String.valueOf(regionId))) {
                        return true;
                    }
                }
               b = queryIsExist(rregionId,AreaId);
            }

        }

        return b;


    }


    /**查询该地区是否已存在
     * @param requestBean
     * @return
     */
    public ResponseBean queryCityIsExist(RequestBean requestBean){
        int currentPage = requestBean.getRequestParamInteger("currentPage",1);
        int pageSize = requestBean.getRequestParamInteger("pageSize",10);
        Integer regionId = requestBean.getRequestParamInteger("region_id");
         ResponseBean responseBean = requestBean.getResponseBean();
        List<String> shippingAreaId= (List<String>) requestBean.getRequestParam("shipping_area_ids");
        List<String> AreaIds=shippingDAO.queryRegionId(shippingAreaId);
        String shippingAreaIds = null;
        shippingAreaIds = AreaIds.get(0);
        for(int i =1;i<AreaIds.size();i++){
            shippingAreaIds =shippingAreaIds+","+ AreaIds.get(i);
        }
        String[] AreaId = shippingAreaIds.split(",");
        boolean b = queryIsExist(regionId,AreaId);
        if(b==true){
            responseBean.setResult(ResultConstant.ERROR);
        }else{
            responseBean.setResult(ResultConstant.SUCCESS);
        }
        return  responseBean;
    }

    /**查询省市区/县节点
     * @param requestBean
     * @return
     */
    public ResponseBean findParentNode(RequestBean requestBean) {
        Long regionId = requestBean.getRequestParamLong("region_id");
        Map<String, Object> shippingMap = new HashMap<>();
        shippingMap.put("region_id", regionId);
        ResponseBean responseBean = requestBean.getResponseBean();
        List<Map<String, Object>> parentNodeList=new ArrayList<>();
        Map<String, Object> rootNode=new HashMap<>();
        rootNode.put("value",1);
        rootNode.put("label","中国");
        parentNodeList.add(rootNode);
        List<Map<String, Object>> parentNode = shippingDAO.queryRegionParents(null);
        getRegionNodeChildren(parentNode, regionId);
        rootNode.put("children",parentNode);
        responseBean.addResultItem("parentRegionList", parentNodeList);
        responseBean.setResult(ResultConstant.SUCCESS);
        return responseBean;
    }

    /**遍历子节点
     * @param list
     * @param regionId
     */
    private void getRegionNodeChildren(List<Map<String, Object>> list, Long regionId) {
        Iterator<Map<String, Object>> itList = list.listIterator();
        while (itList.hasNext()) {
            Map<String, Object> region = itList.next();
            Long rregionId = MapUtils.getLong(region, "region_id");
            Long rregionType = MapUtils.getLong(region, "region_type");
            if (rregionId.equals(regionId)) {
                itList.remove();
            } else {
                String regionName = MapUtils.getString(region, "region_name");
                region.clear();
                region.put("label", regionName);
                region.put("value", rregionId);
                if (rregionType != 3){
                    List<Map<String, Object>> childrenList = shippingDAO.queryRegionParents(rregionId);
                    if (childrenList.size() > 0) {
                        region.put("children", childrenList);
                        getRegionNodeChildren(childrenList, rregionId);
                    }
                }
            }
        }
    }



    /**查询运费模板
     * @param requestBean
     * @return
     */
    public ResponseBean queryFreightTemplate(RequestBean requestBean){
        Integer shopId = requestBean.getRequestParamInteger("id");
        Integer shippingTempletId = requestBean.getRequestParamInteger("shipping_templet_id");
        int currentPage = requestBean.getRequestParamInteger("currentPage",1);
        int pageSize = requestBean.getRequestParamInteger("pageSize",10);
        Map<String,Object> shippingMap = new HashMap<>();
        shippingMap.put("shopId",shopId);
        shippingMap.put("shippingTempletId",shippingTempletId);
        ResponseBean responseBean = requestBean.getResponseBean();
        Page<Map<String,Object>> page = new Page<>(currentPage,pageSize);
        List<Map<String,Object>> FreightTemplateList=shippingDAO.queryFreightTemplate(page,shippingMap);
        try{
            for(int i=0;i<FreightTemplateList.size();i++){
                StringBuffer sb=new StringBuffer();
                Map<String,Object>FreightTemplateListMap=FreightTemplateList.get(i);
                String actionList=(String)FreightTemplateListMap.get("shipping_area_ids");
                List<String> FreightTemplateListDesc=new ArrayList<String>();
                if(actionList!=null){
                    String[]shippingAreaIds=actionList.split(",");
                    FreightTemplateListDesc= shippingDAO.queryTemplateDesc(shippingAreaIds);
                }
                for(int j=0;j<FreightTemplateListDesc.size();j++){
                    sb.append(FreightTemplateListDesc.get(j)).append(',');
                }
                String actionDesc =sb.toString();
                if(actionDesc.length()>0){
                    actionDesc=actionDesc.substring(0,actionDesc.length()-1);
                }
                FreightTemplateListMap.put("shipping_area_ids",actionDesc);
                FreightTemplateList.set(i,FreightTemplateListMap);
            }
            page.setRecords(FreightTemplateList);
            responseBean.addResultPageItem("FreightTemplateList",page);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }

        return  responseBean;
    }




    /**添加运费模板
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addFrightTemplet(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        String shippingName = requestBean.getRequestParamString("shipping_name");
        List<Map<String,Object>> shippingList = shippingDAO.queryShippingId(shippingName);
        Map<String, Object> shippingMap = new HashMap<>();
        for(int i=0;i<shippingList.size();i++) {
            shippingMap = shippingList.get(i);
        }
        String shippingTempletId = requestBean.getRequestParamString("shipping_templet_id");
        String shippingAreaName = requestBean.getRequestParamString("shipping_area_name");
        String shippingFeeType = requestBean.getRequestParamString("shipping_fee_type");
        Integer shippingFirstFee = requestBean.getRequestParamInteger("shipping_first_fee");
        Integer shippingSecFee = requestBean.getRequestParamInteger("shipping_sec_fee");
        Integer shippingFreeFee = requestBean.getRequestParamInteger("shipping_free_fee");
        Integer shippingGoodsFee = requestBean.getRequestParamInteger("shipping_goods_fee");
        List<String> shippingAreaId=null;
        shippingAreaId= (List<String>) requestBean.getRequestParam("shipping_area_id");
        List<String> AreaIds=shippingDAO.queryRegionId(shippingAreaId);
        String shippingAreaIds = null;
        shippingAreaIds = AreaIds.get(0);
        for(int i =1;i<AreaIds.size();i++){
            shippingAreaIds =shippingAreaIds+","+ AreaIds.get(i);
        }

        Map<String, Object> shippingTempletMap = new HashMap<>(6);
        shippingTempletMap.put("shippingId",shippingMap.get("shipping_id"));
        shippingTempletMap.put("shippingTempletId",shippingTempletId);
        shippingTempletMap.put("shippingAreaName",shippingAreaName);
        shippingTempletMap.put("shippingFeeType",shippingFeeType);
        shippingTempletMap.put("shippingFirstFee",shippingFirstFee);
        shippingTempletMap.put("shippingSecFee",shippingSecFee);
        shippingTempletMap.put("shippingFreeFee",shippingFreeFee);
        shippingTempletMap.put("shippingGoodsFee",shippingGoodsFee);
        shippingTempletMap.put("shippingAreaIds",shippingAreaIds);
        try{
            int num = shippingDAO.addFrightTemplet(shippingTempletMap);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }

    /**修改配送模板
     * @param requestBean
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean updateShippingTemplet(RequestBean requestBean) {
        ResponseBean responseBean = requestBean.getResponseBean();
        Integer shippingTempletId = requestBean.getRequestParamInteger("shipping_templet_id");
        String shippingTempletName = requestBean.getRequestParamString("shipping_templet_name");
        String shippingTitle = requestBean.getRequestParamString("shipping_title");
        Map<String, Object> shippingTempletMap = new HashMap<>(6);
        shippingTempletMap.put("shippingTempletId",shippingTempletId);
        shippingTempletMap.put("shippingTempletName",shippingTempletName);
        shippingTempletMap.put("shippingTitle",shippingTitle);
        try{
            int num = shippingDAO.updateShippingTemplet(shippingTempletMap);
            responseBean.setResult(ResultConstant.SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            responseBean.setResult(ResultConstant.ERROR);
            throw new RuntimeException();
        }
        return responseBean;
    }


}
